import App from './app';
import config from '@config/index';
import database from '@config/database';
import logger from '@utils/logger';
import { seedUsers } from '@database/seeds/001-create-admin-user';
import { seedSettings } from '@database/seeds/002-init-settings';

/**
 * 启动应用程序
 */
async function startServer(): Promise<void> {
  try {
    // 连接数据库
    logger.info('Connecting to databases...');
    await database.connectMongoDB();
    await database.connectRedis();
    logger.info('Database connections established');

    // 运行种子数据 (创建演示用户)
    logger.info('Seeding demo users...');
    await seedUsers();
    logger.info('Demo users seeded successfully');

    // 初始化系统设置
    logger.info('Initializing system settings...');
    await seedSettings();
    logger.info('System settings initialized');

    // 创建并启动应用
    const app = new App();
    app.listen();

    // 定期健康检查
    setInterval(async () => {
      try {
        const health = await database.checkConnections();
        if (!health.mongodb || !health.redis) {
          logger.warn('Database health check failed:', health);
        }
      } catch (error) {
        logger.error('Health check error:', error as Error);
      }
    }, 30000); // 每30秒检查一次

  } catch (error) {
    console.error('Failed to start server:', error);
    logger.error('Failed to start server:', error as Error);
    process.exit(1);
  }
}

// 处理未捕获的异常
process.on('uncaughtException', (error: Error) => {
  console.error('Uncaught Exception:', error);
  console.error('Stack:', error.stack);
  logger.error('Uncaught Exception:', error);
  process.exit(1);
});

process.on('unhandledRejection', (reason: any) => {
  console.error('Unhandled Rejection:', reason);
  logger.error('Unhandled Rejection:', reason);
  process.exit(1);
});

// 启动服务器
startServer();